package com.scut.online_black_market.controller;

import com.scut.online_black_market.dto.JwtResponse;
import com.scut.online_black_market.mapper.PersonalMapper;
import com.scut.online_black_market.utility.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * create by yellowBroke on 2020年11月3日 08点56分
 * 登录认证接口
 */
@RestController
@Api(value = "认证接口", tags = "认证接口")
public class AuthorizationController {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private PersonalMapper personalMapper;

    @ApiOperation("登录认证")
    @RequestMapping(value = "/auth/{studentNumber}/{password}", method = RequestMethod.POST)
    public ResponseEntity<JwtResponse> auth(@PathVariable String studentNumber,@PathVariable String password) {

        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(studentNumber, password));

        Map<String, Object> claims = new HashMap<>();
        claims.put("username", personalMapper.selectById(studentNumber).getNickname());

        String jwt = jwtUtil.generateToken(studentNumber, claims);
        return ResponseEntity.ok(new JwtResponse(jwt));
    }
}
